import React, { useState } from 'react';
import { useModel, useRequest } from 'umi';
import {
  PageHeader,
  Descriptions,
  Statistic,
  Modal,
  Button,
  Form,
  Input,
  message,
} from 'antd';
import { FormInstance } from 'antd/es/form';

import { updateUserInfo } from '@/services/umi-demo/user';

import './index.less';

const Center: React.FC<{}> = () => {
  const { initialState } = useModel('@@initialState');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const { currentUser }: any = initialState;
  const formRef = React.createRef<FormInstance>();
  const { loading, run, error } = useRequest(updateUserInfo, {
    manual: true,
    onSuccess: () => {
      message.success('成功！');
      setIsModalVisible(false);
      formRef.current!.resetFields();
    },
  });

  const onReset = () => {
    formRef.current!.resetFields();
  };

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = async (values: any) => {
    let id = currentUser?.id;
    let params: API.updateUserInfoParams = {
      id: id,
    };
    let body: API.UserInfoEntity = {
      password: values.password,
    };

    run(params, body);

    if (error) {
      return;
    }
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const renderContent = () => {
    return (
      <Descriptions size="small" column={2}>
        <Descriptions.Item label="账号">
          {currentUser?.username}
        </Descriptions.Item>
        <Descriptions.Item label="用户名">
          {currentUser?.username}
        </Descriptions.Item>
        <Descriptions.Item label="创建日期">
          {currentUser?.createDate}
        </Descriptions.Item>
        <Descriptions.Item label="更新日期">
          {currentUser?.updateDate}
        </Descriptions.Item>
      </Descriptions>
    );
  };

  const extraContent = (
    <div
      style={{
        display: 'flex',
        width: 'max-content',
        justifyContent: 'flex-end',
      }}
    >
      <Statistic
        title="状态"
        value={currentUser?.valid ? '有效' : '无效'}
        style={{
          marginRight: 32,
        }}
      />
    </div>
  );

  const Content = ({ children, extra }: any) => (
    <div className="content">
      <div className="main">{children}</div>
      <div className="extra">{extra}</div>
    </div>
  );

  /** 更新密码Modal */
  const updatePasswordModal = () => {
    return (
      <Modal
        title="修改密码"
        footer={null}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        width={400}
        centered={true}
      >
        <Form
          layout="horizontal"
          labelAlign="right"
          labelCol={{
            span: 6,
          }}
          wrapperCol={{ span: 16 }}
          ref={formRef}
          onFinish={handleOk}
        >
          <Form.Item
            name="oldPassword"
            label="旧密码"
            rules={[
              {
                required: true,
                message: '不能为空!',
              },
            ]}
          >
            <Input.Password placeholder="请输入旧密码" />
          </Form.Item>
          <Form.Item
            name="password"
            label="新密码"
            rules={[
              {
                required: true,
                message: '不能为空!',
              },
            ]}
          >
            <Input.Password placeholder="请输入新密码" />
          </Form.Item>
          <Form.Item
            name="confirm"
            label="确认密码"
            dependencies={['password']}
            rules={[
              {
                required: true,
                message: '不能为空!',
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('密码不一致!'));
                },
              }),
            ]}
          >
            <Input.Password placeholder="请确认密码" />
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 8,
            }}
          >
            <Button type="primary" htmlType="submit" loading={loading}>
              提交
            </Button>
            <Button htmlType="button" onClick={onReset}>
              清空
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    );
  };

  return (
    <div>
      <PageHeader
        className="site-page-header"
        ghost={false}
        title="个人中心"
        extra={[
          <Button key="1" type="primary" onClick={showModal}>
            修改密码
          </Button>,
          <Button key="2">更新个人信息</Button>,
        ]}
      >
        {updatePasswordModal()}
        <Content extra={extraContent}>{renderContent()}</Content>
      </PageHeader>
    </div>
  );
};

export default Center;
